package com.wie.staffhubpro.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wie.staffhubpro.constant.MessageConstant;
import com.wie.staffhubpro.domain.dto.LoginDTO;
import com.wie.staffhubpro.domain.dto.Register1DTO;
import com.wie.staffhubpro.domain.dto.Register2DTO;
import com.wie.staffhubpro.domain.entity.Emp;
import com.wie.staffhubpro.domain.entity.User;
import com.wie.staffhubpro.domain.vo.RegisterVO;
import com.wie.staffhubpro.domain.vo.UserVO;
import com.wie.staffhubpro.exception.*;
import com.wie.staffhubpro.mapper.EmpMapper;
import com.wie.staffhubpro.service.UserService;
import com.wie.staffhubpro.mapper.UserMapper;
import com.wie.staffhubpro.utils.MD5Utils;
import org.apache.logging.log4j.message.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.security.auth.login.AccountNotFoundException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author WiedersehenM
* @description 针对表【user】的数据库操作Service实现
* @createDate 2025-06-27 14:55:15
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private EmpMapper empMapper;

    /**
     * 用户注册阶段一
     */
    public RegisterVO registerPre(Register1DTO registerDTO) {
        Emp emp = empMapper.selectById(registerDTO.getEmpId());
        // 判断用户是否存在
        if (emp == null || !registerDTO.getEmpName().equals(emp.getEmpName()) || !registerDTO.getDeptId().equals(emp.getDeptId())) {
            throw new EmployeeNotExistException(MessageConstant.EMPLOYEE_NOT_EXIST);
        }
        // 员工仅允许注册一个账号, 查找该员工是否存在账号
        if (emp.getRoleId() == 3) {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("emp_id", emp.getId());
            List<User> userList = userMapper.selectList(queryWrapper);
            if (!userList.isEmpty()) {
                throw new EmployeeMaxAccountException(MessageConstant.EMPLOYEE_MAX_ACCOUNT);
            }
        }

        RegisterVO registerVO = new RegisterVO();
        registerVO.setRoleId(emp.getRoleId());
        return registerVO;
    }

    /**
     * 注册第二阶段
     */
    @Transactional
    public Void register(Register2DTO registerDTO) {
        // 校验用户权限
        Integer roleId = registerDTO.getRoleId();
        Emp emp = empMapper.selectById(registerDTO.getEmpId());
        // 若权限不匹配，则抛出异常
        if (emp.getRoleId() > roleId) {
            throw new PermissionMismatchException(MessageConstant.PERMISSION_MISMATCH);
        }
        // 校验 username 是否重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", registerDTO.getUsername());
        List<User> userList = userMapper.selectList(queryWrapper);
        if (!userList.isEmpty()) {
            throw new UserAlreadyExistException(MessageConstant.USER_ALREADY_EXIST);
        }
        // 部长仅允许注册两个账号，roleId = 2 and roleId = 3
        if (emp.getRoleId() == 2) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("emp_id", emp.getId());
            List<User> userList2 = userMapper.selectByMap(map);
            if (userList2.size() >= 2) {
                throw new EmployeeMaxAccountException(MessageConstant.EMPLOYEE_MAX_ACCOUNT);
            } else if (userList2.size() == 1) {
                User user2 = userList2.get(0);
                if (user2.getRoleId().equals(registerDTO.getRoleId())) {
                    throw new MaxAccountReachedException(MessageConstant.MAX_ACCOUNT_REACHED);
                } else if (user2.getRoleId() == 1) {
                    throw new PermissionMismatchException(MessageConstant.PERMISSION_MISMATCH);
                }
            }
        }
        // 管理员仅允许注册两个账号，roleId = 1 and roleId = 3
        if (emp.getRoleId() == 3) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("emp_id", emp.getId());
            List<User> userList2 = userMapper.selectByMap(map);
            if (userList2.size() >= 2) {
                throw new EmployeeMaxAccountException(MessageConstant.EMPLOYEE_MAX_ACCOUNT);
            } else if (userList2.size() == 1) {
                User user2 = userList2.get(0);
                if (user2.getRoleId().equals(registerDTO.getRoleId())) {
                    throw new MaxAccountReachedException(MessageConstant.MAX_ACCOUNT_REACHED);
                } else if (user2.getRoleId() == 2) {
                    throw new PermissionMismatchException(MessageConstant.PERMISSION_MISMATCH);
                }
            }
        }
        // md5加密用户密码
        String md5Password = MD5Utils.encode(registerDTO.getPassword());
        // 将用户保存至数据库
        User user = new User().builder()
        .username(registerDTO.getUsername())
        .password(md5Password)
        .empId(registerDTO.getEmpId())
        .roleId(registerDTO.getRoleId())
        .status("在线")
        .creatTime(LocalDateTime.now())
        .updateTime(LocalDateTime.now())
        .build();
        userMapper.insert(user);
        return null;
    }

    /**
     * 用户登录
     */
    public User login(LoginDTO loginDTO) throws AccountNotFoundException {
        String username = loginDTO.getUsername();
        String password = loginDTO.getPassword();
        // 对密码进行md5加密
        String loginPassword = MD5Utils.encode(password);
        //根据用户名查询数据库中的数据
        List<User> userList = lambdaQuery()
                .eq(User::getUsername, username)
                .list();
        if (userList == null || userList.isEmpty()) {
            throw new NotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        User user = userList.get(0);
        //校验用户
        if (!loginPassword.equals(user.getPassword())) {
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }
        return user;
    }

    /**
     * 获取当前用户信息
     */
    public UserVO getUserInfo(Integer userId) {
        User user = userMapper.selectById(userId);
        // 查询该用户的 deptId;
        Emp emp = empMapper.selectById(user.getEmpId());
        // 封装 UserVO
        UserVO userVO = new UserVO().builder()
                .id(user.getId())
                .empId(emp.getId())
                .empName(emp.getEmpName())
                .deptId(emp.getDeptId())
                .username(user.getUsername())
                .status(user.getStatus())
                .roleId(user.getRoleId())
                .build();
        return userVO;
    }
}




